<script setup>
  /** Accordion
   *
   * A collapsible titled section
   *
   * The title is permanently displayed and acts as a toggle to hide/show the body
   *
   * a11y inspired by https://www.w3.org/WAI/ARIA/apg/patterns/accordion/examples/accordion/
   */

  import { computed, toRef, watchEffect } from 'vue'
  import { uniqueId } from '@/helpers/utils'

  import Icon from '@/components/Icon.vue'

  const props = defineProps({
    initialCollapsedState: { type: Boolean, default: true },
  })
  // On crée une variable reactive pour stocker un état local du collapse
  const collapsedState = toRef(props.initialCollapsedState)

  // On écoute les changements de la prop initialCollapsedState
  // qui est prioritaire sur le statut "local"
  watchEffect(() => (collapsedState.value = props.initialCollapsedState))

  const panelDomId = uniqueId('accordionPanel')
  const titleDomId = uniqueId('accordionTitle')

  const toggleCollapse = () => (collapsedState.value = !collapsedState.value)

  const actionTitle = computed(() =>
    collapsedState.value ? 'Afficher le contenu' : 'Masquer le contenu'
  )
</script>

<template>
  <div class="separate_block border_left_block">
    <h4 class="collapse_title title">
      <a
        href="#"
        :aria-expanded="!collapsedState"
        :title="actionTitle"
        :aria-label="actionTitle"
        :aria-controls="panelDomId"
        :id="titleDomId"
        @click="toggleCollapse"
      >
        <Icon class="arrow" name="chevron-down" />
        <slot name="title"></slot>
      </a>
    </h4>
    <div
      class="collapse_content"
      :id="panelDomId"
      :aria-labelledby="titleDomId"
      :hidden="collapsedState"
    >
      <div class="collapse in">
        <div class="panel-body">
          <slot name="body"></slot>
        </div>
      </div>
    </div>
  </div>
</template>
